/* eslint-disable @typescript-eslint/no-shadow */
import { nestedCityCode } from '@/components/assets/nestedCityCode';
import type { ProFormInstance } from '@ant-design/pro-components';
import { ProCard } from '@ant-design/pro-components';
import {
  ProFormCascader,
  ProFormDigit,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProForm } from '@ant-design/pro-form/lib/layouts';
import { FooterToolbar } from '@ant-design/pro-layout';
import { Button, Col, Collapse, message, Row, Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import styles from '../index.less';
import { applyParkItem, gateCameraItem, getParkDetail } from '../service';
import type { getParkDetails, ZoneForm } from '../types';
import { addParkBase } from '../utils';
import { optionsSchemeItem } from '../../park-charge/service';
import _ from 'lodash';

const { Panel } = Collapse;

interface addProps {
  close: (e: boolean) => void;
  id?: string;
}

export default (props: addProps) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;

  const { close, id } = props;
  const secondRef = useRef();

  const formRef = useRef<ProFormInstance>();

  const [parkDetails, setParkDetails] = useState<getParkDetails>();
  const [spinVisible, setSpinVisible] = useState(false);

  useEffect(() => {
    setSpinVisible(true);
    getParkDetail(id!).then((res) => {
      if (res) {
        setParkDetails(res.data);
      }
    });
  }, []);
  useEffect(() => {
    if (parkDetails) {
      const details = _.cloneDeep(parkDetails);
      delete details.schemeId;
      const gateChannels: any = details?.channels.map((item, index) => {
        delete item.masterCamera?.cameraId;
        delete item.secondCamera?.cameraId;
        delete item.autoRelease;
        delete item.releaseMode;
        return {
          ...item,
        };
      });
      console.log('gateChannels', gateChannels);

      setTimeout(() => {
        formRef.current?.setFieldsValue({
          ...parkDetails,
          schemeId: { value: parkDetails?.schemeId, label: parkDetails?.schemeName },
          addressCode: getCityArray(String(parkDetails?.addressCode)),
          gateChannels: gateChannels,
        });
      }, 1);

      setSpinVisible(false);
    }
  }, [parkDetails]);
  function getCityArray(code: string) {
    // const code = parkDetails?.addressCode ? parkDetails?.addressCode : 0;
    if (code == undefined || code == '0' || code == 'null') {
      return;
    }
    if (String(code).endsWith('0000')) {
      return [];
    } else if (!String(code).endsWith('0000') && String(code).endsWith('00')) {
      const city = code.substring(0, 4) + '00';
      return [city, code];
    } else if (!String(code).endsWith('0000') && !String(code).endsWith('00')) {
      const province = code.substring(0, 2) + '0000';
      const city1 = code.substring(0, 4) + '00';
      if (
        code.startsWith('31') ||
        code.startsWith('50') ||
        code.startsWith('11') ||
        code.startsWith('12')
      ) {
        return [province, code];
      } else {
        return [province, city1, code];
      }
    }
    return '-';
  }
  return (
    <Spin spinning={spinVisible}>
      <ProForm<ZoneForm>
        formRef={formRef}
        submitter={{
          // 完全自定义整个区域
          render: (props, doms) => {
            return [
              <FooterToolbar key="addFooterBar">
                <Button type="primary" key="submit" onClick={() => props.form?.submit?.()}>
                  提交
                </Button>
              </FooterToolbar>,
            ];
          },
        }}
        onFinish={async (values) => {
          const res = await applyParkItem({
            ...values,
            gateChannels: values.gateChannels?.map((item) => {
              return {
                ...item,
                autoRelease: item.autoRelease?.toString(),
                releaseMode: item.releaseMode?.toString(),
              };
            }),
            schemeId:
              (values.schemeId.value == null ? '' : values.schemeId.value) || values.schemeId,
            addressCode: values.addressCode && values.addressCode[values.addressCode.length - 1],
            tenantId: parkDetails?.tenantId || tenantId,
            id,
          });
          if (res) {
            if (res.code === 0) {
              close(false);
              message.success('更新成功');
              return true;
            } else {
              message.error(`更新失败 ${res.message}`);
              return false;
            }
          }
          return false;
        }}
        title="更新停车场"
        // contextMenu="wwdawdawd"
      >
        <ProCard
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>基础设置</div>}
          className={styles.card}
          style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}
          bordered={false}
        >
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'停车场名称'}
                name="name"
                rules={[{ required: true, message: '请输入停车场名称' }]}
                placeholder="请输入停车场名称"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormDigit
                label={'最大超时离场时间（分钟）'}
                name="maxLeaveTime"
                rules={[{ required: true, message: '请输入最大超时离场时间' }]}
                placeholder="请输入最大超时离场时间"
              />
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <ProFormDigit
                label={'停车场总车位数'}
                name="spaceTotalCount"
                rules={[{ required: true, message: '请输入车场总车位数' }]}
                placeholder="请输入车场总车位数"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormDigit
                label={'停车场可用车位数'}
                name="spaceCount"
                rules={[{ required: true, message: '请输入停车场可用车位数' }]}
                placeholder="请输入停车场可用车位数"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              {parkDetails?.tenantId && (
                <ProFormSelect
                  showSearch
                  label={'收费规则'}
                  name="schemeId"
                  key={`approver`}
                  fieldProps={{
                    style: {
                      width: '100%',
                    },
                  }}
                  params={{ page: 1, pageSize: 10 }}
                  request={async (params, props) => {
                    const res = await optionsSchemeItem({
                      ...params,
                      name: props.text,
                      tenantId: tenantId == '1' ? parkDetails?.tenantId : tenantId!,
                    });
                    if (res && res.code == 0)
                      return res.data.list.map((item: { id: any; name: any }, index: any) => {
                        return {
                          value: item.id,
                          label: item.name,
                        };
                      });
                  }}
                  debounceTime={300}
                  placeholder="请选择收费规则"
                  rules={[{ required: true, message: '请选择收费规则' }]}
                />
              )}
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <ProFormCascader
                label={'停车场地址'}
                name="addressCode"
                placeholder="请选择停车场地址"
                fieldProps={{
                  fieldNames: { label: 'name', value: 'code', children: 'children' },
                  showSearch: true,
                  options: nestedCityCode,
                }}
                rules={[{ required: true, message: '请选择停车场地址' }]}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'停车场联系人'}
                name="connectUser"
                initialValue={parkDetails?.creatorName}
                placeholder="请填写停车场联系人"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormText
                label={'停车场联系方式'}
                name="phone"
                placeholder="请填写停车场联系方式"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <ProFormTextArea
                label={'停车场简单描述'}
                name="desc"
                placeholder="请填写停车场简单描述"
              />
            </Col>
          </Row>
        </ProCard>
        <ProCard
          style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0 }}
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>通道配置</div>}
          bordered={false}
        >
          <ProFormList
            creatorButtonProps={{
              creatorButtonText: '添加通道',
            }}
            name="gateChannels"
            // actionGuard={{
            //   beforeAddRow: async (defaultValue, insertIndex, count) => {
            //     return new Promise((resolve) => {
            //       resolve(true);
            //       console.log(defaultValue?.name, insertIndex, count);
            //     });
            //   },
            // }}
            itemRender={({ listDom, action }, { record }) => {
              return (
                <ProForm.Item noStyle>
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'flex-start',
                    }}
                  >
                    {listDom}
                    {action}
                  </div>
                </ProForm.Item>
              );
            }}
          >
            {(
              meta, //当前行的基本信息
              index, //当前的行号
              action, //操作行的快捷方法
              count, //总行数
            ) => (
              <Collapse
                style={{ marginBottom: 10 }}
                collapsible="header"
                defaultActiveKey={[
                  '0',
                  '1',
                  '2',
                  '3',
                  '4',
                  '5',
                  '6',
                  '7',
                  '8',
                  '9',
                  '10',
                ]} /*  onChange={onChange} */
              >
                <Panel header={`通道 ${index + 1}`} key={`${index}`}>
                  <Row gutter={16}>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormText
                        key={`q${index}`}
                        label={'通道名称'}
                        name="channelName"
                        rules={[{ required: true, message: '通道名称不能为空' }]}
                        placeholder="自定义通道名称"
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormRadio.Group
                        key={`w${index}`}
                        name="channelType"
                        label="通道类型"
                        options={addParkBase.channelType.map((item, index) => ({
                          value: index + 1,
                          label: item,
                        }))}
                        placeholder="请选择通道类型"
                        rules={[{ required: true, message: '请选择通道类型' }]}
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSelect
                        options={addParkBase.releaseMode.map((item, index) => ({
                          key: String(index + 1),
                          value: String(index + 1),
                          label: item,
                        }))}
                        key={`e${index}`}
                        name="releaseMode"
                        fieldProps={{
                          mode: 'multiple',
                        }}
                        style={{ width: '100%' }}
                        label={`放行模式`}
                        initialValue={
                          parkDetails?.channels[index]
                            ? parkDetails?.channels[index].releaseMode?.split(',')
                            : undefined
                        }
                        placeholder="选择通道放行模式（可多选）"
                        rules={[{ required: true, message: '请选择放行模式' }]}
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSelect
                        options={addParkBase.autoRelease.map((item, index) => ({
                          key: String(index + 1),
                          value: String(index + 1),
                          label: item,
                        }))}
                        key={`approver${index}`}
                        fieldProps={{
                          mode: 'multiple',
                        }}
                        initialValue={
                          parkDetails?.channels[index]
                            ? Number(parkDetails?.channels[index]?.autoRelease![0])
                              ? parkDetails?.channels[index].autoRelease?.split(',')
                              : undefined
                            : undefined
                        }
                        style={{ width: '100%' }}
                        label={'放行规则'}
                        name="autoRelease"
                        rules={[{ required: true, message: '请选择通道放行规则' }]}
                        placeholder="选择通道放行规则（可多选）"
                      />
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSelect
                        showSearch
                        initialValue={
                          parkDetails?.channels[index]
                            ? parkDetails?.channels[index]?.masterCamera?.cameraId
                              ? Number(parkDetails?.channels[index]?.masterCamera?.cameraId)
                              : ''
                            : ''
                        }
                        key={index + 'master'}
                        label={'主相机配置'}
                        name={['masterCamera', 'cameraId']}
                        params={{ page: 1, pageSize: 10 }}
                        request={async (params, props) => {
                          const res: any = await gateCameraItem({
                            ...params,
                            // name: props.text,

                            tenantId: Number(tenantId!),
                          });
                          if (res)
                            return res.data.list.map((item: { id: any; name: any }, index: any) => {
                              return {
                                value: item.id,
                                label: item.name,
                              };
                            });
                        }}
                        placeholder="请选择主相机"
                        rules={[
                          {
                            required: true,
                            message: '请选择主相机',
                          },
                        ]}
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSwitch
                        name={['masterCamera', 'enable']}
                        label="是否启用主相机"
                        initialValue={true}
                        fieldProps={{
                          checkedChildren: '开启',
                          unCheckedChildren: '关闭',
                          defaultChecked: true,
                        }}
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSelect
                        showSearch
                        fieldRef={secondRef}
                        key={index + 'second'}
                        label={'辅助相机配置'}
                        initialValue={
                          parkDetails?.channels[index]
                            ? parkDetails?.channels[index]?.secondCamera?.cameraId
                              ? Number(parkDetails?.channels[index]?.secondCamera?.cameraId)
                              : ''
                            : ''
                        }
                        name={['secondCamera', 'cameraId']}
                        params={{ page: 1, pageSize: 10 }}
                        request={async (params, props) => {
                          const res: any = await gateCameraItem({
                            ...params,
                            // name: props.text,
                            tenantId: Number(tenantId!),
                          });
                          if (res)
                            return res.data.list.map((item: { id: any; name: any }, index: any) => {
                              return {
                                value: item.id,
                                label: item.name,
                              };
                            });
                        }}
                        rules={[
                          {
                            required: true,
                            message: '请选择辅助相机配置',
                          },
                        ]}
                        placeholder="选择辅助相机"
                      />
                    </Col>
                    <Col lg={6} md={12} sm={24}>
                      <ProFormSwitch
                        initialValue={true}
                        name={['secondCamera', 'enable']}
                        label="是否启用辅助相机"
                        fieldProps={{
                          checkedChildren: '开启',
                          unCheckedChildren: '关闭',
                          defaultChecked: true,
                        }}
                      />
                    </Col>
                  </Row>
                </Panel>
              </Collapse>
            )}
          </ProFormList>
        </ProCard>
      </ProForm>
    </Spin>
  );
};
